package com.eds.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        // 设置较长的超时时间以适应AI服务可能的延迟
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(5000); // 连接超时时间（毫秒）
        factory.setReadTimeout(30000);   // 读取超时时间（毫秒）

        restTemplate.setRequestFactory(factory);

        // 添加请求拦截器用于日志记录和错误处理
        restTemplate.setInterceptors(Collections.singletonList((request, body, execution) -> {
            // 记录开始时间
            long startTime = System.currentTimeMillis();

            // 执行请求
            ClientHttpResponse response = null;
            try {
                response = execution.execute(request, body);

                // 记录请求时长和状态
                long duration = System.currentTimeMillis() - startTime;
                System.out.printf("API请求执行完成 - 方法: %s, URL: %s, 状态: %s, 耗时: %dms%n",
                        request.getMethod(), request.getURI(), response.getStatusCode(), duration);

                return response;
            } catch (Exception e) {
                // 记录异常
                System.err.printf("API请求异常 - 方法: %s, URL: %s, 异常: %s%n",
                        request.getMethod(), request.getURI(), e.getMessage());
                throw e;
            }
        }));

        return restTemplate;
    }
}